package com.yykj.tencent.im.server.service.impl;

import com.yykj.tencent.im.server.bean.request.PortraitGetRequest;
import com.yykj.tencent.im.server.bean.request.PortraitSetRequest;
import com.yykj.tencent.im.server.bean.request.ProfileItem;
import com.yykj.tencent.im.server.bean.response.GetAppidGroupListResult;
import com.yykj.tencent.im.server.bean.response.PortraitGetResult;
import com.yykj.tencent.im.server.bean.response.PortraitSetResult;
import com.yykj.tencent.im.server.bean.response.UserProfileItem;
import com.yykj.tencent.im.server.dto.ContactDTO;
import com.yykj.tencent.im.server.exception.TimException;
import com.yykj.tencent.im.server.form.UserProfileForm;
import com.yykj.tencent.im.server.model.entity.UserProfile;
import com.yykj.tencent.im.server.model.repository.C2CMessageRepository;
import com.yykj.tencent.im.server.model.repository.UserProfileRepository;
import com.yykj.tencent.im.server.service.ProfileService;
import com.yykj.tencent.im.server.core.TimUtil;
import com.yykj.tencent.im.server.utils.Constant;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ProfileServiceImpl implements ProfileService {

    @Value("${environment}")
    private String environment;

    private UserProfileRepository userProfileRepository;

    @Autowired
    public void setUserProfileRepository(UserProfileRepository userProfileRepository){
        this.userProfileRepository = userProfileRepository;
    }

    /**
     * 版本
     */
    private final String Version = "v4";

    /**
     * 资料管理服务名
     */
    private static final String SERVICE_NAME = "profile";

    /**
     * 资料管理相关命令字
     */
    private static final String PORTRAIT_SET_COMMAND = "portrait_set";
    private static final String PORTRAIT_GET_COMMAND = "portrait_get";

    /**
     * 请求接口
     */
    private final String api_url = "%s/%s/%s";

    /**
     * 设置资料
     */
    @SneakyThrows
    @Override
    public PortraitSetResult portraitSet(UserProfileForm form){
        if(form.getFromAccount() == null){
            throw new TimException("设置账号的UserID不能为空");
        }
        if(form.getName() == null){
            throw new TimException("输入真实姓名");
        }
        List<ProfileItem> lstItems = new ArrayList<>();
        lstItems.add(new ProfileItem("Tag_Profile_IM_Image",form.getImage()));
        lstItems.add(new ProfileItem("Tag_Profile_IM_Nick",form.getName()));
        lstItems.add(new ProfileItem("Tag_Profile_Custom_Hospital",form.getHospital()));
        lstItems.add(new ProfileItem("Tag_Profile_Custom_DepName",form.getDepName()));
        lstItems.add(new ProfileItem("Tag_Profile_Custom_Officer",form.getOfficer()));
        lstItems.add(new ProfileItem("Tag_Profile_Custom_Phone",form.getPhone()));
        lstItems.add(new ProfileItem("Tag_Profile_Custom_Client",form.getClient()));

        PortraitSetRequest portraitSetRequest = PortraitSetRequest.builder()
                .fromAccount(form.getFromAccount())
                .profileItemList(lstItems)
                .build();
        String api = String.format(api_url, Version, SERVICE_NAME,PORTRAIT_SET_COMMAND);
        PortraitSetResult r = TimUtil.post(api,portraitSetRequest, PortraitSetResult.class);

        //保存到数据库里
        UserProfile profile = new UserProfile();
        BeanUtils.copyProperties(form,profile);
        profile.setEnvironment(environment);
        userProfileRepository.save(profile);

        return r;
    }

    /**
     * 拉取资料
    */
    @SneakyThrows
    @Override
    public PortraitGetResult getUserProfile(String userId){
        if(userId == null || userId.isEmpty()){
            throw new TimException("账号的UserID不能为空");
        }
        List<String> userIds = new ArrayList<>();
        userIds.add(userId);
        List<String> tagList = new ArrayList<>();
        tagList.add(Constant.UserProfileTag.IM_Image);
        tagList.add(Constant.UserProfileTag.IM_DEPNAME);
        tagList.add(Constant.UserProfileTag.IM_PHONE);
        tagList.add(Constant.UserProfileTag.IM_HOSPITAL);
        tagList.add(Constant.UserProfileTag.IM_OFFICER);
        tagList.add(Constant.UserProfileTag.IM_Nick);
        tagList.add(Constant.UserProfileTag.IM_CLIENT);

        PortraitGetRequest portraitGetRequest = PortraitGetRequest.builder()
                .toAccount(userIds)
                .tagList(tagList)
                .build();

        String api = String.format(api_url, Version, SERVICE_NAME,PORTRAIT_GET_COMMAND);
        return TimUtil.post(api,portraitGetRequest, PortraitGetResult.class);
    }

    /**
     * 好友资料
     */
    @SneakyThrows
    @Override
    public List<ContactDTO> getFriendProfile(List<String> accountIds) {
        if(accountIds.size() == 0){
            throw new TimException("账号的UserID不能为空");
        }
        List<String> tagList = new ArrayList<>();
        tagList.add(Constant.UserProfileTag.IM_Image);
        tagList.add(Constant.UserProfileTag.IM_Nick);

        PortraitGetRequest portraitGetRequest = PortraitGetRequest.builder()
                .toAccount(accountIds)
                .tagList(tagList)
                .build();

        String api = String.format(api_url, Version, SERVICE_NAME,PORTRAIT_GET_COMMAND);
        PortraitGetResult result = TimUtil.post(api,portraitGetRequest, PortraitGetResult.class);
        List<ContactDTO> contactDTOS = new ArrayList<>();
        List<UserProfileItem> items = result.getUserProfileItemList();
        for(UserProfileItem item : items){
            ContactDTO contactDTO = new ContactDTO();
            contactDTO.setAccountId(item.getToAccount());
            List<ProfileItem> profileItems = item.getProfileItemList();
            for(ProfileItem profileItem:profileItems){
                String tag = profileItem.getTag();
                if(tag.equals("Tag_Profile_IM_Nick")){
                    contactDTO.setName(profileItem.getValue());
                }
                if(tag.equals("Tag_Profile_IM_Image")){
                    contactDTO.setFaceUrl(profileItem.getValue());
                }
            }
            contactDTOS.add(contactDTO);
        }
        return contactDTOS;
    }


}
